﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Components.Enum;
using Controls;
using Components;
using Model.Enum;
using UI.Common;
using UI.Lib.Factory;
using UI.Lib;


namespace UI.ParentForm
{
    public partial class BaseNonPageMain : BaseForm
    {
        private BindingManagerBase BindingManager;
        protected bool IsChildLoadComplete = false; //子页面是否已经加载好了
        private int gridViewHeadWidth = 0; //实际的表格列宽度
        protected int fixedColumn = -1; //锁定列
        CheckBox chk = null; //是否启用高级查询的复选框
        private bool _searchMk = false; //绑定数据时是否是点击了查询
        private List<Model.TextValuePair> cols = null;

        #region 属性

        private bool _isNullData = false;
        protected bool IsNullData
        { get { return _isNullData; } }

        public UI.Common.Pager MyPager = null;

        public BaseNonPageMain()
        {
            InitializeComponent();

            if (!base.isDebug)
            {
                _pageInit();
                InitGrid(); //c初始化表格控件
                BindGrid(); //给Grid绑定数据
                AddToolButton();
            }
        }

        public BaseNonPageMain(string modulecode, string action)
            : this()
        {
            this.ModuleCode = modulecode;
            this.Action = action;
        }

        #endregion

        /// <summary>
        /// 初始化表格控件
        /// </summary>
        protected virtual void InitGrid()
        {
            DataTable dtCol = PageCache.GetLayout(this.GetType().FullName, PageControlType.MainCtl);
            if (dtCol == null) return;

            this.dgvMain.AutoGenerateColumns = false;
            PsDataGridViewTextBoxColumn col = null;
            Model.TextValuePair tv = null; //绑定下拉框
            int width = 0;

            foreach (DataRow dr in dtCol.Rows)
            {
                col = new PsDataGridViewTextBoxColumn();
                col.Name = dr["colname"].ToString();
                col.DataPropertyName = col.Name;
                col.ColType = (PsDataType)Convert.ToInt32(dr["coltype"]);
                col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                col.HeaderText = dr["headcn"].ToString();
                col.IsQuery = ("y" == dr["isquery"].ToString().ToLower());
                col.Visible = ("n" == dr["isshow"].ToString().ToLower()); //数据库中isshow y和n刚好搞反了
                width = Validation.ToInt(dr["columnwidth"]); //字段宽度 
                col.Width = col.Visible == false ? 0 : ( //字段宽度
                        (0 == width) ? GridViewUtil.Entity.GetHeadWidth(col.HeaderText) : width
                    );
                gridViewHeadWidth += col.Width;

                //列别名
                col.OtherName = (Validation.IsNull(dr["oname"]) ? col.Name : dr["oname"].ToString());

                col.ReadOnly = true;

                if (col.IsQuery && col.Visible == true)
                {
                    tv = new Model.TextValuePair(col.HeaderText, col.Name);
                    this.cbxField.Items.Add(tv);

                    tv.DataType = col.ColType;
                    tv.OtherName = col.OtherName;

                    if (null == cols)
                    {
                        cols = new List<Model.TextValuePair>();
                    }

                    cols.Add(tv);
                }

                this.dgvMain.Columns.Add(col);
            }

            if (this.cbxField.Items.Count > 0) this.cbxField.SelectedIndex = 0;
        }

        //初始化
        private void _pageInit()
        {
            //隔行换色
            this.dgvMain.RowsDefaultCellStyle.BackColor = Color.White;
            this.dgvMain.BackgroundColor = Color.FromArgb(236, 241, 245);
            this.dgvMain.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(246, 250, 255);
        }

        //字段下拉框选项改变了的时候，改变操作符下拉框的选项
        protected virtual void cbxField_SelectedIndexChanged(object sender, EventArgs e)
        {
            Model.TextValuePair tv = this.cbxField.SelectedItem as Model.TextValuePair;//当选择的字段名称改变时，重置操作符
            if (tv == null) return;

            string value = txtInput.Text;
            PsDataGridViewTextBoxColumn dc = this.dgvMain.Columns[tv.Value] as PsDataGridViewTextBoxColumn;
            UI.Lib.SearchHelper.GetOperateList(dc.ColType, this.cbxOp); //绑定下拉框
        }

        protected virtual void BindGrid()
        {
            bool mk = _searchMk; //点击查询按钮的标识
            _searchMk = false;

            if (null == MyPager)
            {
                MyPager = new UI.Common.Pager();
            }

            //设置数据源的指针位置
            if (BindingManager != null) BindingManager.Position = -1;

            //得到界面上查询的条件
            bool continues = false;
            MyPager.AutoWhere = GetSearchWhere(ref continues);
            if (continues == false) return;

            if (!this.BeforeBindData()) return;

            MyPager.IsReadDbSource = true;
            MyPager.PageName = this.GetType().FullName;
            MyPager.Comcode = Context.Comocde; //2011-03-05新加入，为了适应自定义排序的需求
            MyPager.Usercode = Context.LoginName;

            UpdatePager(MyPager); //更新分页的页面信息

            Model.ReturnPageData data = null;
            if (MyPager == null) return;
            if (MyPager.IsReadDbSource) //需要从数据库中读取数据源
            {
                data = CommonHelper.Entity.GetPageList(MyPager);
            }
            else data = SetDataSource();

            if (null == data || data.AllRowCount == 0)
            {
                _isNullData = true;
                this.dgvMain.DataSource = null;
                if (mk)
                {
                    MessageBox.Show("未能查询到相关数据！", "提示");
                }
                return;
            }

            _isNullData = false;
            this.dgvMain.DataSource = data.CurrnetPageData.DefaultView; //绑定表格

            if (this.BindingManager != null) //当前的可能是重新加载数据源
            {
                _AddDefaultEvent();
            }

            AfterDataGridBind();//当数据绑定之后执行
        }

        protected virtual bool BeforeBindData() { return true; }

        /// <summary>
        /// 更新页面信息
        /// </summary>
        protected virtual void UpdatePager(Common.Pager pager)
        { }

        /// <summary>
        /// 当数据绑定之后执行
        /// </summary>
        protected virtual void AfterDataGridBind() { }

        /// <summary>
        /// 得到Main页面数据源的where
        /// </summary>
        /// <returns></returns>
        protected virtual string GetSearchWhere(ref bool continues)
        {
            continues = true;

            //两种情况，一般普通查询和高级查询
            if (chk == null || chk.Checked == false)
            {
                string value = txtInput.Text;
                if (string.IsNullOrEmpty(value)) return "";

                Model.TextValuePair tv = this.cbxField.SelectedItem as Model.TextValuePair;
                if (tv == null) return "";

                Model.TextValuePair op = this.cbxOp.SelectedItem as Model.TextValuePair;
                if (op == null) return "";

                PsDataGridViewTextBoxColumn dc = this.dgvMain.Columns[tv.Value] as PsDataGridViewTextBoxColumn;

                continues = true;
                return UI.Lib.SearchHelper.GetSearchWhere(tv, dc, value, op, dc.ColType);
            }

            return "";
        }

        //得到数据源
        protected virtual Model.ReturnPageData SetDataSource()
        {
            return null;
        }

        protected bool isClickSearchBtn = false;

        //点击查找
        private void btnSearch_Click(object sender, EventArgs e)
        {
            isClickSearchBtn = true;
            BindGrid();
            isClickSearchBtn = false;
        }

        //页面改变时，触发数据源
        private void winpg_PageIndexChanged(object sender, EventArgs e)
        {
            BindGrid();
        }

        private void tspView_Click(object sender, EventArgs e)
        {

        }

        private void tspAdd_Click(object sender, EventArgs e)
        {

        }

        private void tspEdit_Click(object sender, EventArgs e)
        {

        }

        private void tspDel_Click(object sender, EventArgs e)
        {

        }

        #region 虚拟方法

        protected virtual void OnViewClick(ToolStripButton btn, DataGridViewRow row) { }

        protected virtual void OnAddClick(ToolStripButton btn) { }

        protected virtual void OnEditClick(ToolStripButton btn, DataGridViewRow row) { }

        protected virtual void OnDeleteClick(ToolStripButton btn, DataGridViewRow row) { }
        #endregion

        /// <summary>
        /// 得到选中行 方便公用
        /// </summary>
        /// <returns></returns>
        protected DataGridViewRow GetSelectedRow()
        {
            if (0 == this.dgvMain.Rows.Count || 0 == this.dgvMain.SelectedRows.Count) return null;
            return this.dgvMain.SelectedRows[0];
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!base.isDebug)
            {
                CheckRight(); //检查权限

                FixedColumn();
            }

            _AddDefaultEvent();

            _SetFontSize();

            _SetToolBtnStyle();

            isLoadOk = true;
        }

        /// <summary>
        /// 是否验证权限
        /// </summary>
        protected bool IsCheckRight = true;

        #region 权限相关

        private void CheckRight()
        {
            if (!IsCheckRight) return;

            string[] ps = Validation.ToString(CommonHelper.Entity.GetActionList(this.ModuleCode)).Split(',');
            if (ps.Length == 0) //没有权限访问
            {
                MessageBox.Show("您没有操作该模块的任何权限，请联系管理员！", "提示");
                this.InitOk = false;
                this.Close();
                return;
            }

            foreach (ToolStripItem item in tspTop.Items)
            {
                if (item is ToolStripButton)
                {
                    if (item.Tag == null) item.Visible = false; //没有设置Tag的按钮隐藏
                    if (item.Tag.ToString() != "S" && Array.IndexOf(ps, item.Tag.ToString()) == -1)
                        item.Visible = false;
                }
            }
        }

        #endregion


        private void BaseMain_Leave(object sender, EventArgs e)
        {

        }

        private void BaseMain_FormClosing(object sender, FormClosingEventArgs e)
        {
        }

        protected void BaseMain_ClientSizeChanged(object sender, EventArgs e)
        {
            AutoSize();

            //如果单元格的宽度之和小于我的GridView的宽度，则自动填充满
            this.dgvMain.AutoSizeColumnsMode = (gridViewHeadWidth < this.dgvMain.ClientSize.Width) ? DataGridViewAutoSizeColumnsMode.Fill :
                 DataGridViewAutoSizeColumnsMode.None;
        }

        protected void BaseMain_Shown(object sender, EventArgs e)
        {
            BaseMain_ClientSizeChanged(sender, e);
        }

        protected virtual void AutoSize()
        {

        }

        protected virtual void AddToolButton() { }

        protected void FixedColumn()
        {
            if (fixedColumn < 0 || fixedColumn > this.dgvMain.ColumnCount) return;
            this.dgvMain.Columns[fixedColumn].Frozen = true;
        }

        /// <summary>
        /// 行改变之后触发
        /// </summary>
        /// <param name="rowIndex"></param>
        protected virtual void AfterRowChanged(int rowIndex) { }

        //添加默认事件
        private void _AddDefaultEvent()
        {
            object datasource = this.dgvMain.DataSource;
            if (datasource == null) return;
            BindingManager = this.BindingContext[datasource];
            BindingManager.PositionChanged -= new EventHandler(BindingManager_PositionChanged);
            BindingManager.PositionChanged += new EventHandler(BindingManager_PositionChanged);

            if (0 != this.dgvMain.Rows.Count) AfterRowChanged(0);
        }

        void BindingManager_PositionChanged(object sender, EventArgs e)
        {
            int tRowIndex = BindingManager.Position;

            AfterRowChanged(tRowIndex);
        }

        //设置字体大小
        void _SetFontSize()
        {
            this.tspTop.Font = dgvMain.Font = Global.AllFont;
        }

        private void BaseMain_KeyDown(object sender, KeyEventArgs e)
        {
            /*
            switch (e.KeyCode)
            {
                case Keys.Insert:    //按下的是Insert
                    if (CanClickButton(this.tspAdd)) tspAdd_Click(this.tspAdd, null);
                    break;
                case Keys.F2:    //按下的是F2，修改
                    if (CanClickButton(this.tspEdit)) tspEdit_Click(this.tspEdit, null);
                    break;
                case Keys.Delete:    //按下的是Del
                    if (CanClickButton(this.tspDel)) tspDel_Click(this.tspDel, null);
                    break;
                case Keys.End:    //按下的是End == 进入查询 让文本框得到焦点
                    if (this.txtInput.Visible == true) txtInput.Focus();
                    break;
                case Keys.Home:    //按下的是Home，Id号为104 == 执行查询
                    if (CanClickButton(this.btnSearch)) btnSearch_Click(btnSearch, null);
                    break;
                case Keys.PageDown:    //按下的是page down，Id号为105 == 查看明细
                    if (CanClickButton(this.tspView)) tspView_Click(tspView, null);
                    break;
                case Keys.PageUp:    //按下的是page up，Id号为106 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F4:    //按下的是F4，Id号为107 == 返回及关闭
                    this.Close();
                    break;
                case Keys.F5:    //按下的是F5，Id号为108 == 调用子菜单
                    break;
                case Keys.F9: //排序
                    if (null != btnOrder && CanClickButton(btnOrder)) btnOrder.PerformClick();
                    break;
            } */
        }

        void _SetToolBtnStyle()
        {
            ToolStripButton btn = null;
            foreach (ToolStripItem item in this.tspTop.Items)
            {
                if (item is ToolStripButton)
                {
                    btn = item as ToolStripButton;
                    btn.BackgroundImage = base.Imgs.Images[3];
                }
            }
        }
    }
}
